package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.UserDao;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;

import java.util.List;

@Service(interfaceClass = UserService.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;



    @Override
    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }

    @Override
    public PageInfo<User> findPage(QueryPageBean queryPageBean) {
        if (!StringUtils.isEmpty(queryPageBean.getQueryString())){
            queryPageBean.setQueryString("%"+queryPageBean.getQueryString()+"%");
        }

        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        List<User> page = userDao.findByCondition(queryPageBean.getQueryString());

        PageInfo pageInfo = new PageInfo(page);
        return pageInfo;
    }

    @Override
    public List<Role> findRole() {
        return userDao.findRole();
    }

    @Override
    public void add(User user, Integer[] roleIds) {

        userDao.add(user);
        Integer userId = user.getId();
        for (Integer roleId : roleIds) {
            userDao.addRoleUser(userId,roleId);
        }
    }

    @Override
    public void edit(User user, Integer[] roleIds) {
        userDao.edit(user);
        Integer userIds = user.getId();
        userDao.delete(userIds);
        for (Integer roleId : roleIds) {
            userDao.addRoleUser(userIds,roleId);
        }
    }

    @Override
    public List<Integer> findUserById(Integer userId) {
        return userDao.findUserById(userId);
    }


    /**
     * 通过id删除用户
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        userDao.deleteUserIdRoleId(id);
        userDao.deleteById(id);
    }


}
